package pl.ydp.utils
{
	public class Version
	{
		private var m_major:uint;
		private var m_minor:uint;
		private var m_micro:uint;
		private var m_build:String;
		
		public function Version( ifo:String = null )
		{
			if ( ifo==null ) {
				m_major = 0;
				m_minor = 0;
				m_micro = 0;
				m_build = ""
			} else {
				var build:Array = ifo.split( "-", 2 );
				var versionss:String = build[0];
				if ( build.length>1 )
					m_build = build[1];
				
				var versions:Array = ifo.split(".",4);
				m_major = parseVersionComponent(versions[0]);
				if ( versions.length>1 )
					m_minor = parseVersionComponent(versions[1]);
				if ( versions.length>2 )
					m_micro = parseVersionComponent(versions[2]);
				if ( versions.length>3 && m_build==null )
					m_build = versions[3];
				if ( m_build==null )
					m_build = "";
			}
		}
		
		public function get major():uint {
			return m_major;
		}
		public function get minor():uint {
			return m_minor;
		}
		public function get micro():uint {
			return m_micro;
		}
		public function get build():String {
			return m_build;
		}
		public function compare( v2:Version ):int {
			var v:int = m_major-v2.m_major;
			if ( v!=0 )
				return v;
			v = m_minor-v2.m_minor;
			if ( v!=0 )
				return v;
			v = m_micro-v2.m_micro;
			if ( v!=0 )
				return v;
			
			// if possible compare build entry as number
			var b1:Number = parseInt(m_build);
			var b2:Number = parseInt(v2.m_build);
			if ( !isNaN(b1) && !isNaN(b2) )
				return b1<b2 ? -1 : (b2>b1 ? 1 : 0);
			
			return m_build<v2.m_build ? -1 :
				(m_build>v2.m_build ? 1 : 0);
		}
		public function toString():String {
			var res:String = m_major.toString();
			if ( m_minor>0 || m_micro>0 )
				res += "."+m_minor;
			if ( m_micro>0 )
				res += "."+m_micro;
			if ( m_build!="" )
				res += "-"+m_build;
			
			return res;
		}
		
		private static const TRIM_REGEX:RegExp = /^[\s]*(.*?)[\s]*/s;
		static public function trim( str:String ):String {
	        if (str == null) return '';
	        
	        var res:Array = TRIM_REGEX.exec(str);
	        if ( res==null )
	        	return str;
	        return res[1];
		}
		
		static public function parseVersionComponent( ifo:String ):uint {
			if ( ifo==null )
				return 0;
			
			var v:Number = parseInt( ifo, 10 );
			if( isNaN(v) )
				v = 0;
			return uint( v );
		} 

	}
}